package com.nacos.novelzoolserver.provider;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.nacos.novelcommon.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * 线路回退，统一返回
 *
 * @author zy 刘会发
 * @since 2020/4/3
 */
@Component
public class ZuulFallbackProvider implements FallbackProvider {
    private static final Logger LOGGER = LoggerFactory.getLogger(ZuulFallbackProvider.class);

    @Override
    public String getRoute() {
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        System.out.println("route = " + route + ", cause = " + cause);
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return 200;
            }

            @Override
            public String getStatusText() throws IOException {
                return "OK";
            }

            @Override
            public void close() {
                LOGGER.info("请求时间:{}---->无法请求服务:{},mes:{}", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), route, cause);
            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream(JSONUtil.parse(Result.failed()).toString().getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
}
